//
//  LoginCheckController.m
//  MClient
//
//  Created by Zhouyi on 10-12-2.
//  Copyright 2010 __MyCompanyName__. All rights reserved.
//

#import "LoginCheckController.h"
#import "MServerDAO.h"
#import "MServerConfigCache.h"
#import "MServerJsonDAO.h"
#import "MCTabBarController.h"
#import "MenuController.h"
#import "UIDevice+IdentifierAddition.h"
@interface LoginCheckController(Private)
//UITextField *checkCode;
@end

@implementation LoginCheckController

@synthesize partyId;
@synthesize userId;
@synthesize password;

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
	[super viewDidLoad];
	self.title = @"登录验证";
	[self leftBarButton:@"重新登录" withStyle:UIBarButtonItemStylePlain selector:@selector(logout:)];//huotianjun 注销改为重新登录
    
	self.tableview.backgroundColor = [UIColor clearColor];
	statJsonDao = [[loginStat alloc] init];
	// 用一个UINavigationBar以便于再push到下一页面时隐藏navigationcontroller自带的UINavigationBar时最顶上出现白边
	UINavigationBar* naviBar = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, -navigationBarHeight, self.width, navigationBarHeight)];
	naviBar.tintColor = self.userDefaults.skin_navigationBarColor;
	naviBar.tag = -200;
	naviBar.hidden = YES;
	UILabel* title = [[[UILabel alloc] initWithFrame:naviBar.bounds] autorelease];
	title.backgroundColor = [UIColor clearColor];
	title.text = self.title;
	title.textAlignment = UITextAlignmentCenter;
	title.textColor = [UIColor whiteColor];
	title.font = [UIFont boldSystemFontOfSize:20];
	[naviBar addSubview:title];
	[self.view addSubview:naviBar];
}

- (void)viewWillDisappear:(BOOL)animated {
	[super viewWillDisappear:animated];
	[self.view viewWithTag:-200].hidden = NO;
}

- (void)dealloc {
	[statJsonDao release];
	[partyId release];
	[userId release];
	[password release];
	[checkCode release];
    [super dealloc];
}

#pragma mark ---- UITableView方法 ----
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
	return 2;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
	UITableViewCell *cell;
	if (indexPath.row == 0) {
		static NSString *cellIdentifier_Style1 = @"cellIdentifier_Style1";
		cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier_Style1];
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier_Style1] autorelease];
			cell.accessoryType = UITableViewCellAccessoryNone;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			cell.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
			cell.textLabel.backgroundColor = [UIColor clearColor];
			cell.textLabel.text = @"验证码";
			
			UITextField *field = [[UITextField alloc] initWithFrame:CGRectMake(100, 12, 100, 27)];
			[field addTarget:self action:@selector(textFieldDone:) forControlEvents:UIControlEventEditingDidEndOnExit];
			field.borderStyle = UITextBorderStyleNone;
			field.clearsOnBeginEditing = NO;
			field.returnKeyType = UIReturnKeyDone;
			field.placeholder = @"输入验证码";
			field.textColor = [UIColor colorWithRed:0.282 green:0.341 blue:0.455 alpha:1];
			field.backgroundColor = [UIColor clearColor];
			field.autoresizingMask = nTableCellAutoresizingMask;
			[cell addSubview:field];
			field.tag = indexPath.row+100;
			[field release];
			
			UIWebView *checkImage = [[UIWebView alloc] initWithFrame:CGRectMake(self.width - 80, 12, 60, 20)];
			checkImage.backgroundColor = [UIColor clearColor];
			checkImage.autoresizingMask = nCheckCodeAutoresizingMask;
			checkImage.tag = -3;
			NSString *checkImageUrl = [NSString stringWithFormat:@"%@%@%@", self.userDefaults.current_ServerUrl, @"/beapp/tpcode?pid=", partyId];
			checkImage.scalesPageToFit = NO;
			[checkImage loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:checkImageUrl]]];
			[cell addSubview:checkImage];
			[checkImage release];
		}
		UITextField *field = (UITextField *)[cell viewWithTag:indexPath.row+100];
		checkCode = [field retain];
	} else {
		static NSString *cellIdentifier_Style2 = @"cellIdentifier_Style2";
		cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier_Style2];
		if (cell == nil) {
			cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier_Style2] autorelease];
			cell.accessoryType = UITableViewCellAccessoryNone;
			cell.selectionStyle = UITableViewCellSelectionStyleNone;
			cell.backgroundColor = [[UIColor whiteColor] colorWithAlphaComponent:0.7];
			
			UIButton* applyBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
			applyBtn.frame = CGRectMake(35, 7, 80, 30);
			applyBtn.autoresizingMask = nTableCellAutoresizingMask;
			[applyBtn setTitle:@"确定" forState:UIControlStateNormal];
			[applyBtn addTarget:self action:@selector(sendApply) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:applyBtn];
			[applyBtn release];
			
			UIButton* resetBtn = [[UIButton buttonWithType:UIButtonTypeRoundedRect] retain];
			resetBtn.frame = CGRectMake(200, 7, 80, 30);
			resetBtn.autoresizingMask = nTableCellAutoresizingMask;
			[resetBtn setTitle:@"刷新" forState:UIControlStateNormal];
			[resetBtn addTarget:self action:@selector(refresh) forControlEvents:UIControlEventTouchUpInside];
			[cell.contentView addSubview:resetBtn];
			[resetBtn release];
		}
	}
	return cell;
}

#pragma mark ---- 事件处理方法 ----
- (void)logoutApp {
	[self messageBox:@"确定重新登录?" //huotianjun 注销改为重新登录
			 message:nil
			delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确定"];
}

- (void) logout: (id) sender {
	[self logoutApp];
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
	if (buttonIndex == 1) {
		[[self findFirstResponder] resignFirstResponder];
		[self.appDelegate.navController popToRootViewControllerAnimated:YES];
	}
}

// 向服务器发送修改请求
- (void)sendApply
{
	if (nil == checkCode.text || [@"" isEqualToString:checkCode.text]) {
		[self messageBox:@"提示" 
				 message:@"请输入验证码！"
				delegate:self
	   cancelButtonTitle:nil
	   otherButtonTitles:@"确定"];
		return;
	}
	[[self findFirstResponder] resignFirstResponder];
	MServerJsonDAO *mServerDAOInstance = [[MServerJsonDAO alloc] init];
	[mServerDAOInstance initServerUrl];
	[[MServerDAO sharedInstance] loginAsync:partyId
									 userId:userId
								   password:password
									   imei:[[UIDevice currentDevice] uniqueGlobalDeviceIdentifier]
									   imsi:@""
									  acode:checkCode.text == nil?@"":checkCode.text
								   delegate:self];
}
			 
- (void)getDataFromServerSuccess: (NSMutableDictionary *)returnValue{
	statJsonDao.partyId = partyId;
	statJsonDao.userId = userId;
	statJsonDao.serverUrl = self.userDefaults.current_ServerUrl;
	[statJsonDao sendStatRequest];
	
	self.userDefaults.current_PartyId = partyId;
	self.userDefaults.current_UserId = userId;
	self.userDefaults.current_ServerUrl = self.userDefaults.current_ServerUrl;
	
	if (self.userDefaults.isSavePassword) {
		self.userDefaults.current_Password = password;
	}
	else {
		self.userDefaults.current_Password = @"";
	}
	
	NSMutableDictionary *loginReturn = [returnValue retain];
	
	NSString *timeStamp = [loginReturn objectForKey:@"ldt"];
	
	[[MServerConfigCache sharedInstance] loadCacheFromStore:timeStamp 
													 server:self.userDefaults.current_ServerUrl
													  party:partyId
													   user:userId];
	
	if ([returnValue objectForKey:@"sct"] && [[returnValue objectForKey:@"sct"] count] > 0) {
		MCTabBarController* tabBarController = [[[MCTabBarController alloc] init] autorelease];
		tabBarController.tabBarData = returnValue;
		[self.navigationController pushViewController:tabBarController animated:YES];
	} else {
		MenuController *menuViewController = [[MenuController alloc] init];
		menuViewController.title = [MCFunction getAppName];
		menuViewController.menus = [loginReturn objectForKey:@"app"];
		menuViewController.isApp = YES;
		
		menuViewController.navigationItem.hidesBackButton = YES;
		[self.navigationController pushViewController:menuViewController animated:YES];
		[menuViewController release];
	}
	
	[loginReturn release];	
}
			 
- (void)refresh
{
	NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
	UITableViewCell *cell = [self.tableview cellForRowAtIndexPath:indexPath];
	UIWebView *checkImage = (UIWebView *)[cell viewWithTag:-3];
	NSString *checkImageUrl = [NSString stringWithFormat:@"%@%@%@", self.userDefaults.current_ServerUrl, @"/beapp/tpcode?pid=", partyId];
	[checkImage loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:checkImageUrl]]];
}

#pragma mark --- UIAlertViewDelegate --
- (void) textFieldDone:(id)sender
{
	[sender resignFirstResponder];
}

@end
